import BeautifulSoup
import urllib
import re

from types import NoneType
from lib.aj.snapvideo import VideoWeed
from lib.aj.common.DataObjects import VideoInfo, VIDEO_QUAL_SD
from lib.VideoFromHost import VideoFromHost
import UI


animeFreak='http://www.animefreak.tv'
glossary='/glossary/'

class GrabAnimeFreak:
    fastBrowse = True
    
    def __init__(self, fastBrowse=True):
        self.fastBrowse = fastBrowse
    
    def checkName(self, name):
        try:
            name = str(name)
        except UnicodeEncodeError:
            name = str(name.encode('utf-8'))
        
        return name
    
    
    def getHTML(self, url):    
        self.currenturl = url
        print "[AnimeFreak] Finding URL: "+self.currenturl
        htmlSource = urllib.urlopen(url).read()
        print "[AnimeFreak] Got URL."
        return htmlSource
    
    def cleanInfo(self, string):
        string = str(string)
        string = string.replace(":", "")
        string = string.replace(",", "")
        string = string.split()
        
        ret = ""
        max = len(string)
        i = 0
        for s in string:
            i += 1
            ret = ret + s
            if i < max:
                ret = ret + ", "
            
        
        return ret
    
    def getAnimeSerieInfo(self, url):
        if self.fastBrowse:
            return None
        
        info = {}
        info.setdefault('ICON','None')
        info.setdefault('GENRE','None')
        info.setdefault('EPISODES','None')
        info.setdefault('TYPE','None')
        info.setdefault('AGERATING','None')
        info.setdefault('ABOUT','None')
        
        htmlSource = self.getHTML(url)
        soup = BeautifulSoup.BeautifulSoup(htmlSource, convertEntities=BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
        
        icon = soup.find("img")
        icon = str(icon)
        regs = re.compile('src=\".*jpg\" ')
        icon = regs.search(icon)
        if not isinstance(icon, NoneType):
            icon = icon.group()
            icon = icon.replace('src="',"")
            icon = icon.replace('" ',"")
            info['ICON'] = icon
        
        
        information = soup.findAll('blockquote')
        
        if len(information) is 0:
            return info
        
        block1 = information[0]
        regs = re.compile('\<strong\>.*')
        i = regs.finditer(str(block1))
        
        for m in i:
            m = m.group()
            s = BeautifulSoup.BeautifulSoup(str(m))
            found = s.findAll(text=True)
            strong = str(found[0])
            strong = strong.upper()
            
            if strong.find("GENRE") is not -1:
                genre = self.cleanInfo(found[1])
                info['GENRE']=genre
            elif strong.find("EPISODES") is not -1:
                episodes = self.cleanInfo(found[1])
                info['EPISODES']=episodes
            elif strong.find("TYPE") is not -1:
                type = self.cleanInfo(found[1])
                info['TYPE']=type
            elif strong.find("AGE RATING") is not -1:
                agerating = self.cleanInfo(found[3])
                info['AGERATING']=agerating
                
        print url
        block4 = information[len(information)-1]
        s = BeautifulSoup.BeautifulSoup(str(block4))
        s = s.findAll(text=True)
        info['ABOUT'] = str(s[1])
        
        return info
        
    def listAllSeries(self):
        listURL = animeFreak + '/book'
        
        htmlSource = self.getHTML(listURL)
        soup = BeautifulSoup.BeautifulSoup(htmlSource, convertEntities=BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
        all_list = soup.findAll(href=re.compile("^/watch/"))
        
        for serie in all_list:
            n = str(serie)
            soups = BeautifulSoup.BeautifulSoup(n)
            serieURL = animeFreak + soups.a['href']
            serieName = soups.a.string
            
            serieName = self.checkName(serieName)
            info = self.getAnimeSerieInfo(serieURL)
            
            UI.UI().addItem({'TITLE':serieName, 'MODE':'ANIMESERIE', 'URL':serieURL}, extraInfo=info)
        del all_list
        UI.UI().endOfDirectory()
        
    def listAtoZ(self):
        listURL = animeFreak + '/glossary'
        
        htmlSource = self.getHTML(listURL)
        soup = BeautifulSoup.BeautifulSoup(htmlSource, convertEntities=BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
        char_list = soup.findAll("span", "views-summary views-summary-unformatted")
        
        for char in char_list:
            soups = BeautifulSoup.BeautifulSoup(str(char))
            charURL = animeFreak + soups.a['href']
            
            reg = re.compile("\(\d+\)")
            findNumber = reg.search(str(char))
            seriesCount = findNumber.group()
            
            charName = soups.a.string + ' ' + seriesCount
            
            if self.fastBrowse is False:
                fast = "False"
            else:
                fast = "True"
            
            UI.UI().addItem({'TITLE':charName, 'MODE':'SHOWA2Z', 'URL':charURL, 'FASTBROWSE':fast})
            
        del char_list
        UI.UI().endOfDirectory()
            
    def listSeriesByChar(self, url):
        htmlSource = self.getHTML(url)
        soup = BeautifulSoup.BeautifulSoup(htmlSource, convertEntities=BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
        serieslists = soup.find("table","views-table cols-1")
        soupSeries = BeautifulSoup.BeautifulSoup(str(serieslists))
        serieslist = soupSeries.findAll("a",href=re.compile("^/watch/"))
        
        for serie in serieslist:
            n = str(serie)
            soups = BeautifulSoup.BeautifulSoup(n)
            serieURL = animeFreak + soups.a['href']
            serieName = soups.a.string
            
            serieName = self.checkName(serieName)
            info = self.getAnimeSerieInfo(serieURL)
            
            UI.UI().addItem({'TITLE':serieName, 'MODE':'ANIMESERIE', 'URL':serieURL}, extraInfo=info)
            
        del serieslists
        del serieslist
        UI.UI().endOfDirectory()
        
    def listSerieEpisodes(self, url):
        htmlSource = self.getHTML(url)
        soup = BeautifulSoup.BeautifulSoup(htmlSource, convertEntities=BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
        serieslists = soup.find("ul","menu")
        soupSeries = BeautifulSoup.BeautifulSoup(str(serieslists))
        serieslist = soupSeries.findAll("a",href=re.compile("^/watch/"))
        
        self.fastBrowse = False
        info = self.getAnimeSerieInfo(url)
        
        for serie in serieslist:
            n = str(serie)
            soups = BeautifulSoup.BeautifulSoup(n)
            serieURL = animeFreak + soups.a['href']
            title = soups.a.string
            
            UI.UI().addItem({'TITLE':title, 'MODE':'EPISODE', 'URL':serieURL}, extraInfo=info)
            
        del serieslists
        del serieslist
        UI.UI().endOfDirectory()
    
    def listEpisodeVideoLinks(self, url):
        htmlSource = self.getHTML(url)
        soup = BeautifulSoup.BeautifulSoup(htmlSource, convertEntities=BeautifulSoup.BeautifulSoup.HTML_ENTITIES)
        serieslists = soup.findAll(href=re.compile("^\#English"))
        
        onlyOne = (len(serieslists) == 0)
        
        if onlyOne:
            serieslists = soup.findAll("iframe")
        
        for serie in serieslists:
            n = str(serie)
            soups = BeautifulSoup.BeautifulSoup(n)
            
            linkName = "Video"
            
            if onlyOne is not True:
                linkName = soups.a.string
                
            print n
            
            if onlyOne is not True:
                reg = re.compile("\(.*,")
                link = reg.search(str(n))
                link = link.group()
                link = link.replace("('","")
                link = link.replace("',","")
            else:
                link = str(n)
            
            
            regs = re.compile('src=\".*\" ')
            
            a = urllib.unquote_plus(link)
            
            linkc = regs.search(a)
            
            if not isinstance(linkc, NoneType):
                linkc = linkc.group()
                linkc = linkc.replace('src="',"")
                linkc = linkc.replace('" ',"")
                a = linkc
            
            link = urllib.quote(a, safe="%/:=&?~#!$,;'@()*[]")
            link = VideoFromHost().getVideoURL(link)
            test = str(link)
            print test
            if test.find("[AnimeFreak]") is -1:
                UI.UI().addItem({'TITLE':linkName, 'MODE':'PLAYEPISODE', 'URL':link}, isFolder=False)
            elif onlyOne is not True:
                UI.UI().addItem({'TITLE': "[BROKEN] " + linkName, 'MODE':'NOTSUPPORTEDHOST', 'URL':link})
            
        del serieslists
        UI.UI().endOfDirectory()
        
    def getVideoInfo(self, video_id):
        video_info = VideoWeed.retrieveVideoInfo(video_id)
        print video_info.get_video_link(VIDEO_QUAL_SD)
        
#GrabAnimeFreak().getAnimeSerieInfo('http://www.animefreak.tv/watch/air-gear-english-dubbed-online-free')
#GrabAnimeFreak().listEpisodeVideoLinks('http://www.animefreak.tv/watch/fairy-tail-episode-4-online')